<?php

/**
 * Controller_mail
 */

class Controller_mail extends MyApp {

	public function __construct()
	{

		parent::__construct();


		// 收件箱数
		$row = $this->db->fetchRow("SELECT COUNT(1) AS count FROM `tbl_mail` WHERE mail_to='{$this->user['user_id']}' AND status='1'");
		$count_inbox = (int)$row['count'];

		$this->tpl->assign("count_inbox", $count_inbox);

		$this->model->file  = YOU::loadModel('file');
		$this->model->staff = YOU::loadModel('staff');
		$this->model->user  = YOU::loadModel('user');
	}

	/** 首页 **/
	public function actionIndex()
	{

		$this->tpl->display();
	}

	/** 邮件列表 **/
	public function actionList()
	{
		$type = $this->get->type;
		$s    = $this->get->s;
		$where = " WHERE 1=1 ";

		if (!empty($s)){
			$where .= " AND mail_title LIKE '%{$s}%' ";
		}

		switch ($type){
			// 收件箱
			case "inbox":
				$where .= " AND mail_to='{$this->user['user_id']}' AND status='1' ";
				$this->tpl->assign("type_name", "收件箱");
				break;
				// 发件箱
			case "outbox":
				$where .= " AND mail_from='{$this->user['user_id']}' AND status='1' ";
				$this->tpl->assign("type_name", "发件箱");
				break;
				// 垃圾箱
			case "spambox":
				$where .= " AND (mail_to='{$this->user['user_id']}' OR mail_from='{$this->user['user_id']}') AND status='2' ";
				$this->tpl->assign("type_name", "垃圾箱");
				break;
			default:
				$where .= " AND mail_to='{$this->user['user_id']}' AND status='1' ";
				$this->tpl->assign("type_name", "收件箱");
				break;

		}


		// 分页
		YOU::loadLib('page', "", '0');

		$tmp = $this->db->fetchRow("SELECT COUNT(1) AS count FROM `tbl_mail` {$where} ");
		$count = $tmp['count'];
		$page_total = ceil($count/PAGE_LIMIT);

		// 当前页
		$p = intval($_GET['p']);
		if ($p == 0){
			$p  = 1;
		}
		if ($p > 1){
			$start = PAGE_LIMIT * ($p-1);
		}else{
			$start = 0;
		}

		$mail_lists = $this->db->fetchAll("SELECT * FROM `tbl_mail` {$where} ORDER BY mail_id DESC LIMIT {$start}, ".PAGE_LIMIT."");
		foreach($mail_lists as $key => $value){
			if ($type == "outbox"){
				$mail_lists[$key]['show_name'] = $this->model->user->getNameById($value['mail_to']);
			}else{
				$mail_lists[$key]['show_name'] = $this->model->user->getNameById($value['mail_from']);
			}
		}

		$page = new Page(array('total' => $count, 'perpage' => PAGE_LIMIT));
		$page->next_page   = '下一页>';
		$page->pre_page    = '<上一页';
		$page->style_path  = "static/page_style";

		$this->tpl->assign("page", $page->show(4, "yahoo"));

		$this->tpl->assign("type", $type);
		$this->tpl->assign("count", $count);
		$this->tpl->assign("email_lists", $mail_lists);
		$this->tpl->display("mail/m.mail.list.tpl.php");
	}

	/** 添加邮件 **/
	public function actionAdd()
	{
		// 普通填写 转发
		$type      = $this->get->type;
		$mail_id   = (int)$this->get->mail_id;
		if (!empty($mail_id)){
			$mail_data = $this->db->fetchRow("SELECT * FROM `tbl_mail` WHERE mail_id='{$mail_id}' AND mail_to='{$this->user['user_id']}' ");
			$mail_data['mail_fromname'] = $this->model->user->getNameById($mail_data['mail_from']);
		}
		if (!empty($mail_data['mail_file'])){
			$mail_file = $mail_data['mail_file'];
			$mail_data['mail_file'] = unserialize($mail_data['mail_file']);
			foreach($mail_data['mail_file'] as $k => $v){
				$mail_data['mail_file'][$k]['fsize'] = number_format($v['fsize']/1024);
			}
		}

		switch ($type){
			case "replay":
				$mail_title   = "Re".$mail_data['mail_title'];
				$mail_content = $mail_data['mail_content'];
				break;
			case "forward":
				$mail_title   = "Fw:".$mail_data['mail_title'];
				$mail_content = $mail_data['mail_content'];
				break;

			default:
				$mail_title   = $mail_data['mail_title'];
				$mail_content = $mail_data['mail_content'];
				break;

		}



		if ($_POST){
			$mail_to      = $this->post->mail_to;
			$mail_title   = $this->post->mail_title;
			$mail_content = $this->post->mail_content;

			if(empty($mail_to)){
				Helper_Client::alert("收件人不能为空");
			}
			if(empty($mail_title)){
				Helper_Client::alert("邮件标题不能为空");
			}
			if(empty($mail_content)){
				Helper_Client::alert("请填写邮件内容");
			}

			// staff_id转成user_id
			$mail_to = $this->model->user->getIdByType("staff", $mail_to);

			// 写入数据库
			$info = array(
			"mail_title"   => $mail_title,
			"mail_content" => $mail_content,
			"mail_file"    => $mail_file,
			"mail_from"    => $this->user['user_id'],
			"mail_to"      => $mail_to,
			"is_read"      => 0,
			"read_time"    => "0000-00-00 00:00:00",
			"status"       => 1,
			"create_time"  => date("Y-m-d H:i:s"),
			"update_time"  => "0000-00-00 00:00:00",
			);

			$this->db->do_insert("tbl_mail", $info);
			$mail_id = $this->db->insert_id();

			// 附件上传
			$file = $this->model->file->upload("mail_file", $mail_id, array("txt","ppt", "xls", "xlsx", "docs", "doc", "pdf", "jpg", "png", "gif", "zip", "rar"));
			if (!empty($file)){
				$info = array(
				"mail_file" => serialize(array( 0 => array("fname" => $file['fname'], "fsize" => $file['fsize']))),
				);

				$this->db->do_update("tbl_mail", $info, "mail_id='{$mail_id}'");
			}


			// 跳转
			Helper_Client::reurl("index.php?a=mail.success");

		}
		// 员工列表给下拉
		$staff_lists   = $this->model->staff->getAll();
		$this->tpl->assign("staff_lists", $staff_lists);
		$this->tpl->assign("mail_title", $mail_title);
		$this->tpl->assign("mail_content", $mail_content);
		$this->tpl->assign("mail_data", $mail_data);
		$this->tpl->display("mail/m.mail.add.tpl.php");
	}

	/** 删除邮件到垃圾箱 **/
	public function actionDel()
	{
		$mail_id = (int)$this->get->mail_id;
		$mail_data = $this->db->fetchRow("SELECT * FROM `tbl_mail` WHERE mail_id='{$mail_id}' AND  mail_to='{$this->user['user_id']}' AND status='1'");

		if (empty($mail_data)){
			Helper_Client::alert("邮件不存在");
		}

		// 修改status = 2
		$info = array(
		"status" => 2,
		);
		$this->db->do_update("tbl_mail", $info, "mail_id='{$mail_id}'");

		// 跳转
		Helper_Client::reurl("index.php?a=mail.tip");

	}


	/** 批量删除 **/
	public function actionDelAll()
	{
		$pids = $this->post->pids;
		if (!empty($pids)){
			foreach ($pids as $key => $value){
				$this->db->query("UPDATE `tbl_mail` SET status='2' WHERE mail_to='{$this->user['user_id']}' AND status='1' AND mail_id='{$value}'");
				$this->db->query("UPDATE `tbl_mail` SET status='2' WHERE mail_from='{$this->user['user_id']}' AND status='1' AND mail_id='{$value}'");

			}
		}

		// 跳转
		Helper_Client::location("删除成功", "index.php?a=mail.list&type=inbox");

	}

	/** 批量清空 **/
	public function actionDestoryAll()
	{

		$pids = $this->post->pids;
		if (!empty($pids)){
			foreach ($pids as $key => $value){
				$this->db->query("DELETE FROM `tbl_mail` WHERE mail_to='{$this->user['user_id']}' AND status='2' AND mail_id='{$value}'");

			}
		}

		// 跳转
		Helper_Client::location("永久删除成功", "index.php?a=mail.list&type=spambox");

	}

	/** 清空垃圾箱 **/
	public function actionDestory()
	{
		$this->db->query("DELETE FROM `tbl_mail` WHERE mail_to='{$this->user['user_id']}' AND status='2'");
		// 跳转
		Helper_Client::location("垃圾箱已清空", "index.php?a=mail.list&type=spambox");

	}

	/** 邮件详情 **/
	public function actionInfo()
	{
		$mail_id = (int)$this->get->mail_id;

		$mail_data = $this->db->fetchRow("SELECT * FROM `tbl_mail` WHERE mail_id='{$mail_id}' AND (mail_from='{$this->user['user_id']}' OR mail_to='{$this->user['user_id']}')");

		if (empty($mail_data)){
			Helper_Client::alert("邮件不存在");
		}

		// 如果是收件人查看 更新查看状态
		if ($mail_data['mail_to'] == $this->user['user_id']){
			$info = array(
			"is_read"   => 1,
			"read_time" => date("Y-m-d H:i:s"),
			);
			$this->db->do_update("tbl_mail", $info, "mail_id='{$mail_id}'");

			// 显示可删除
			$this->tpl->assign("is_del", 1);

		}
		$mail_data['mail_fromname'] = $this->model->user->getNameById($mail_data['mail_from']);

		// 附件
		if (!empty($mail_data['mail_file'])){
			$mail_data['mail_file'] = unserialize($mail_data['mail_file']);
			foreach($mail_data['mail_file'] as $k => $v){
				$mail_data['mail_file'][$k]['fsize'] = number_format($v['fsize']/1024);
			}
		}


		// 上一篇
		$row = $this->db->fetchRow("SELECT mail_id FROM `tbl_mail` WHERE mail_id<'{$mail_id}' AND mail_to='{$this->user['user_id']}'");
		if (!empty($row)){
			$this->tpl->assign("mail_last", $row['mail_id']);
		}
		// 下一篇
		$row = $this->db->fetchRow("SELECT mail_id FROM `tbl_mail` WHERE mail_id>'{$mail_id}' AND mail_to='{$this->user['user_id']}'");
		if (!empty($row)){
			$this->tpl->assign("mail_next", $row['mail_id']);
		}

		$this->tpl->assign("mail_id", $mail_id);
		$this->tpl->assign("mail_data", $mail_data);
		$this->tpl->display("mail/m.mail.info.tpl.php");
	}


	/** 文件下载 **/
	public function actionFile()
	{
		$mail_id = (int)$this->get->mail_id;
		$fname   = $this->get->fname;

		$mail_data = $this->db->fetchRow("SELECT * FROM `tbl_mail` WHERE mail_id='{$mail_id}' AND (mail_from='{$this->user['user_id']}' OR mail_to='{$this->user['user_id']}')");
		if (empty($mail_data)){
			Helper_Client::alert("邮件不存在");
		}

		// 展开邮件的附件
		if (!empty($mail_data['mail_file'])){
			$mail_data['mail_file'] = unserialize($mail_data['mail_file']);
			foreach($mail_data['mail_file'] as $k => $v){
				if ($fname == $v['fname']){

					$fpath = UPLOAD_PATH."/mail_file/{$fname}";

					// 输出下载文件头
					header("Content-Disposition: attachment; filename={$fname}");
					// 在线输出
					readfile($fpath);

				}
			}
		}

		Helper_Client::alert("附件不存在");

	}

	/** 发送成功页面 **/
	public function actionSuccess()
	{

		$this->tpl->display("mail/mail.success.tpl.php");
	}

	/** 其他提示页面 **/
	public function actionTip()
	{

		$this->tpl->display("mail/mail.tip.tpl.php");
	}
}

?>